#include "client.h"
#include "serveur.h"
#include <signal.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>

volatile sig_atomic_t VARSIGNAL = 0;

void gestionSignal(int signal, siginfo_t *sig, void *handler)
{
  	VARSIGNAL = 0;
}

void *threadAttenteConnexion(void *arg)
{
  int *socket = arg;

  attenteCommande_Serveur(*socket);
  close(*socket);
  return 0;
}

int main (int argc, char* argv[])
{
  const char* machine;
  const char* port;
  int socket;
  int i;
  pthread_t thread;
  struct sigaction sig;

  sig.sa_handler = NULL;
  sig.sa_sigaction = gestionSignal;
  sig.sa_flags = SA_SIGINFO;
  memset(&(sig.sa_mask), 0, sizeof(sig.sa_mask));
  sig.sa_restorer = NULL;
 	
  for(i = 1; i <= 15; i++)
    if(sigaction(i, &sig, NULL) == -1 && i !=9)
      {
	fprintf(stderr, "Erreur sigaction pour le signal %d\n", i);	
      }
  
  VARSIGNAL = 1;
  if(argc ==2)
    {
      void *res;
      int retval;
      char ret = 'A';
      fd_set rfds, rfds_tot;
      int sClient;
      port= argv[1];
      
      socket = creationSocket_Serveur(port);
      
      FD_ZERO(&rfds_tot);
      FD_SET(socket, &rfds_tot);
      FD_SET(STDIN_FILENO, &rfds_tot);
      do
	{
	  FD_ZERO(&rfds);
	  rfds = rfds_tot;
	  retval = select(FD_SETSIZE, &rfds, NULL, NULL, NULL);
	  if(retval == -1) {
	    if(errno != EINTR)
	      {
		perror("select");
		exit(1);
	      }
	    else 
	      break;
	  }
	  if(FD_ISSET(socket, &rfds))
	    {
	      sClient = attenteConnexion_Serveur(socket);
	      if(pthread_create(&thread, NULL, threadAttenteConnexion, &sClient) != 0)
		{
		  perror("Erreur pthread_create");
		}
	    }
	  if(FD_ISSET(STDIN_FILENO, &rfds))
	    {
	      ret = getc(stdin);
	    }
	 
	  if(VARSIGNAL == 0)
	    {
	      break;
	    }
	}while(ret != 'S');
      VARSIGNAL = 0;
      printf("Fermeture des différents clients\n");
      if(pthread_join(thread, &res) != 0)
	{
	  perror("Erreur pthread_join");
	}
      printf("Bye\n");
    }
  else if(argc ==3)
    {
      machine = argv[1];

      port= argv[2];
      
      socket = connexion_client(machine, port);
      menu_Client(socket);
    }
  else 
    {
      fprintf(stderr, "\nUsage serveur : %s <port> \n", argv[0]);
      fprintf(stderr, "\nUsage client : %s <machine> <port> \n", argv[0]);
      exit(1);
    }
  close(socket);
  return 0;
}
